package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.QuestionApi;
import com.tanhua.model.mongo.Option;
import com.tanhua.model.mongo.Question;
import com.tanhua.model.mongo.Questionnaire;
import com.tanhua.model.vo.OptionVo;
import com.tanhua.model.vo.QuestionVo;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@DubboService
public class QuestionApiImpl implements QuestionApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 获取问卷的问题列表
     * @return
     */
    @Override
    public Map<ObjectId, List<QuestionVo>> getQuestions() {
        List<Question> questions = mongoTemplate.find(new Query(), Question.class);
        List<ObjectId> questionnaireIds = questions.stream().map(Question::getQuestionnaireId).collect(Collectors.toList());

        Map<ObjectId, List<QuestionVo>> result = new HashMap<>();
        for (ObjectId questionnaireId : questionnaireIds) {
            List<QuestionVo> questionList = new ArrayList<>();
             questions.forEach(question -> {
                if (StringUtils.equals(question.getQuestionnaireId().toHexString(), questionnaireId.toHexString())) {
                    QuestionVo vo =  QuestionVo.init(question);
                    //查询题目选项
                    Query optionQuery = new Query(Criteria.where("questionId").is(question.getId().toHexString()));
                    List<Option> options = mongoTemplate.find(optionQuery, Option.class);
                    List<OptionVo> optionVos = options.stream().map(option -> OptionVo.init(option)).collect(Collectors.toList());
                    vo.setOptions(optionVos);
                    questionList.add(vo);
                }
            });

            result.put(questionnaireId, questionList);
        }
        return result;
    }

    /**
     * 根据问题Id查找问卷
     *
     * @return
     */
    @Override
    public Questionnaire findQuestionnaireId(String questionId) {
        Question question = mongoTemplate.findById(new ObjectId(questionId), Question.class);
        return mongoTemplate.findById(question.getQuestionnaireId(), Questionnaire.class);
    }
}
